<template>
  <div class="image-upload">
    <el-upload
      class="upload-demo"
      :action="uploadAction"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :show-file-list="false"
      :accept="accept"
      :disabled="disabled"
    >
      <div v-if="!imageUrl" class="upload-placeholder">
        <el-icon class="upload-icon"><Plus /></el-icon>
        <div class="upload-text">点击上传图片</div>
        <div class="upload-hint">{{ uploadHint }}</div>
      </div>
      <div v-else class="image-preview">
        <img :src="imageUrl" class="uploaded-image" />
        <div class="image-overlay">
          <el-icon class="preview-icon" @click.stop="previewImage" ><ZoomIn /></el-icon>
          <el-icon class="delete-icon" @click.stop="deleteImage"><Delete /></el-icon>
        </div>
      </div>
    </el-upload>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="60%">
      <img :src="imageUrl" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, ZoomIn, Delete } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  imageUrl: {
    type: String,
    default: ''
  },
  accept: {
    type: String,
    default: 'image/*'
  },
  sizeLimit: {
    type: Number,
    default: 2 // MB
  },
  disabled: {
    type: Boolean,
    default: false
  },
  uploadHint: {
    type: String,
    default: '支持 JPG、PNG 格式，大小不超过 2MB'
  }
})

// Emits
const emit = defineEmits(['update:imageUrl'])

// 响应式数据
const previewVisible = ref(false)
const uploading = ref(false)

// 计算属性
const uploadAction = computed(() => {
  // 使用OSS图片上传接口
  return '/housingHub/oss/upload/propertyImages'
})

// 上传前验证
const beforeUpload = (file) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  // 检查文件大小
  const isLimitSize = file.size / 1024 / 1024 < props.sizeLimit
  if (!isLimitSize) {
    ElMessage.error(`图片大小不能超过 ${props.sizeLimit}MB!`)
    return false
  }

  uploading.value = true

  // 允许上传到服务器
  return true
}

// 上传成功回调
const handleSuccess = (response, file) => {
  uploading.value = false

  // 调试：打印响应信息
  console.log('上传响应:', response)
  console.log('响应类型:', typeof response)
  console.log('响应code:', response?.code)
  console.log('响应data:', response?.data)

  // 处理OSS返回的图片URL
  if (response && (response.code === 200 || response.code === "200") && response.data) {
    // OSS接口返回的是完整的URL
    console.log('使用OSS URL:', response.data)
    emit('update:imageUrl', response.data)
    ElMessage.success('上传成功!')
  } else {
    // 如果服务器还没有实现上传接口，临时使用base64
    console.log('使用base64，响应无效:', response)
    const reader = new FileReader()
    reader.onload = (e) => {
      emit('update:imageUrl', e.target.result)
    }
    reader.readAsDataURL(file.raw || file)
    ElMessage.success('上传成功!')
  }
}

// 上传失败回调
const handleError = (error) => {
  uploading.value = false
  ElMessage.error('上传失败!')
  console.error('Upload error:', error)
}

// 预览图片
const previewImage = () => {
  if (props.imageUrl) {
    previewVisible.value = true
  }
}

// 删除图片
const deleteImage = () => {
  emit('update:imageUrl', '')
  ElMessage.success('图片已删除')
}
</script>

<style scoped>
.image-upload {
  display: inline-block;
}

.upload-demo {
  width: 200px;
  height: 200px;
}

:deep(.el-upload) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-upload:hover) {
  border-color: #4A90E2;
}

.upload-placeholder {
  text-align: center;
  color: #8c939d;
  padding: 20px;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 14px;
  margin-bottom: 5px;
  color: #606266;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.image-preview {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.preview-icon,
.delete-icon {
  font-size: 35px;
  color: white;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.preview-icon:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.delete-icon:hover {
  background-color: rgba(255, 0, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-demo,
  :deep(.el-upload),
  .image-preview {
    width: 150px;
    height: 150px;
  }

  .upload-placeholder {
    padding: 15px;
  }

  .upload-icon {
    font-size: 24px;
  }

  .upload-text {
    font-size: 13px;
  }

  .upload-hint {
    font-size: 11px;
  }
}
</style>